package utils;

import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import com.google.gson.Gson;
import merchant.dao.Merchant;
import merchant.dao.MerchantSettlementDetail;
import merchant.entity.RecordOfCharge;
import merchant.entity.SummaryOfCharge;

public class MerchantDAO {

	final String host;
	final HttpClient client = new HttpClient();
	
	public MerchantDAO(final String host){
		this.host = host;
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
				  new DefaultHttpMethodRetryHandler());
	}
	
	public Merchant getMerchant(final String id) throws HttpException, IOException{
		final HttpClient client = new HttpClient();
		final HttpMethod method = new GetMethod(host + "/merchant/showMerchantDetails.json?merchantNumber=" + id);
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();
		method.releaseConnection();
		return new Gson().fromJson(json, Merchant.class);		
	}
	
	public void saveMerchant(final Merchant m) throws HttpException, IOException{
		final PostMethod method = new PostMethod(host + "/merchant/createMerchant.json");
		method.addParameter("merchant", new Gson().toJson(m));
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();
		method.releaseConnection();	
	}

	public MerchantSettlementDetail saveSettlement(MerchantSettlementDetail s) throws IOException {
		final PostMethod method = new PostMethod(host + "/merchant/createSettlementDetail.json");
		method.addParameter("settlement", new Gson().toJson(s));
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();		
		method.releaseConnection();	
		return new Gson().fromJson(json, MerchantSettlementDetail.class);
	}

	public SummaryOfCharge saveSoC(SummaryOfCharge soc) throws IOException  {
		final PostMethod method = new PostMethod(host + "/merchant/createSoc.json");
		method.addParameter("soc", new Gson().toJson(soc));
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();		
		method.releaseConnection();	
		return new Gson().fromJson(json, SummaryOfCharge.class);
	}

	public RecordOfCharge saveRoC(RecordOfCharge roc) throws IOException {
		final PostMethod method = new PostMethod(host + "/merchant/createRoc.json");
		method.addParameter("roc", new Gson().toJson(roc));
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();		
		method.releaseConnection();	
		return new Gson().fromJson(json, RecordOfCharge.class);
	}
	
}
